package org.example;

import com.iflytek.domain.LoginVo;
import com.iflytek.domain.User;
import com.iflytek.service.PermissionService;
import com.iflytek.service.RoleService;
import com.iflytek.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    // 角色权限和对应权限添加 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        LoginVo vo = (LoginVo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (String role : vo.getRoles()) {
            simpleAuthorizationInfo.addRole(role);
            List<String> permissions = roleService.selectPermissionsByRole(role);
            for (String permission : permissions) {
                simpleAuthorizationInfo.addStringPermission(permission);
            }
        }
        return simpleAuthorizationInfo;
    }

    // 用户认证 登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        String username = authenticationToken.getPrincipal().toString();
        User user = userService.selectOne(username);
        if (user == null) {
            return null;
        } else {
            LoginVo loginVo = new LoginVo();
            loginVo.setUser(user);
            // 这里简单模拟，实际需要根据用户ID查询角色和权限
            loginVo.getRoles().add(user.getRole());
            List<String> permissions = roleService.selectPermissionsByRole(user.getRole());
            loginVo.getPermissions().addAll(permissions);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(loginVo, user.getPassword(), null, getName());
            return info;
        }
    }
}